layui.use(['layer', 'form', 'table', 'admin', 'ax', 'func', 'formSelects'], function () {
    var $ = layui.$;
    var layer = layui.layer;
    var form = layui.form;
    var table = layui.table;
    var $ax = layui.ax;
    var admin = layui.admin;
    var func = layui.func;
    
    var formSelects = layui.formSelects;

    /**
     * 系统管理--角色管理
     */
    var Role = {
        tableId: "roleTable",    //表格id
        condition: {
            roleName: ""
        }
    };

    /**
     * 初始化表格的列
     */
    Role.initColumn = function () {
        return [[
            {type: 'checkbox'},
            {field: 'roleId', hide: true, sort: true, title: '角色id'},
            {field: 'name', align: "center", sort: true, title: '名称'},
            {field: 'pName', align: "center", sort: true, title: '上级角色'},
            {field: 'description', align: "center", sort: true, title: '别名'},
            {align: 'center', toolbar: '#tableBar', title: '操作', minWidth: 280}
        ]];
    };

    /**
     * 点击查询按钮
     */
    Role.search = function () {
        var queryData = {};
        queryData['roleName'] = $("#roleName").val();
        table.reload(Role.tableId, {
            where: queryData, page: {curr: 1}
        });
    };

    /**
     * 弹出添加角色
     */
    Role.openAddRole = function () {
        func.open({
            height: 470,
            title: '添加角色',
            content: Feng.ctxPath + '/role/role_add',
            tableId: Role.tableId
        });
    };

    /**
     * 点击编辑角色
     *
     * @param data 点击按钮时候的行数据
     */
    Role.onEditRole = function (data) {
        func.open({
            height: 470,
            title: '修改角色',
            content: Feng.ctxPath + "/role/role_edit?roleId=" + data.roleId,
            tableId: Role.tableId
        });
    };

    /**
     * 导出excel按钮
     */
    Role.exportExcel = function () {
        var checkRows = table.checkStatus(Role.tableId);
        if (checkRows.data.length === 0) {
            Feng.error("请选择要导出的数据");
        } else {
            table.exportFile(tableResult.config.id, checkRows.data, 'xls');
        }
    };

    /**
     * 点击删除角色
     *
     * @param data 点击按钮时候的行数据
     */
    Role.onDeleteRole = function (data) {
        var operation = function () {
            var ajax = new $ax(Feng.ctxPath + "/role/remove", function (result) {
                if (result.code == 500) {
                    Feng.error(result.message);
                    return;
                }
                Feng.success("删除成功!");
                table.reload(Role.tableId);
            }, function (data) {
                Feng.error("删除失败!" + data.responseJSON.message + "!");
            });
            ajax.set("roleId", data.roleId);
            ajax.start();
        };
        Feng.confirm("是否删除角色 " + data.name + "?", operation);
    };

    /**
     * 分配菜单
     *
     * @param data 点击按钮时候的行数据
     */
    Role.roleAssign = function (inData) {
        var cond = {};
        cond['title'] = "权限配置";
        cond['formUrl'] = "common/tree_dlg.html";
        cond['listUrl'] = "/menu/menuTreeListByRoleId/"+inData.roleId;
        cond['extendCond'] = {};
        cond['openMode'] = 'multiple'
        cond['height'] = 550;
        cond['width'] = 400;
        kitFun.show(cond,function (data) {
            var ids = [];
            if(data.length > 0){
                for(var i=0;i<data.length;i++){
                    ids.push(data[i].treeId);
                }
            }
            var ajax = new $ax(Feng.ctxPath + "/role/setAuthority", function (resData) {
                Feng.success("分配角色成功!");
            }, function (data) {
                Feng.error("分配角色失败!" + data.responseJSON.message + "!");
            });
            ajax.setAsync(true);
            ajax.set("ids", ids.join());
            ajax.set("roleId", inData.roleId);
            ajax.start();
        })
    };

    /**
     * 分配菜单
     *
     * @param data 点击按钮时候的行数据
     */
    Role.roleUserAssign = function (inData) {
        var url = $('#role-user-assign');
        var options = {
            type: 1,
            title: '分配用户',
            width: "800",
            height: "300",
            url: url,
            offset: '70px',
            success: function(layero, index){
                //这里因为内容过少, 会被遮挡, 所以简单修改了下样式
                // $('#layui-layer' + index).find("div[class=layui-layer-content]").css("overflow","unset")
                document.getElementById('layui-layer' + index).getElementsByClassName('layui-layer-content')[0].style.overflow = 'unset';
                formSelects.config('userSelect', {
                    response: {
                        statusCode: 200,          //成功状态码
                        statusName: 'code',     //code key
                        msgName: 'message',         //msg key
                        dataName: 'data'        //data key
                    },
                }, true);

                formSelects.render('userSelect', {
                    height: "38px",
                    radio: false,//是否设置为单选模式
                    searchType: "dl",    //搜索框的位置
                    showCount: 0,//多选的label数量, 0,负值,非数字则显示全部
                });
                formSelects.data('userSelect', 'server', {
                    url:  Feng.ctxPath + '/userRole/getUserRoleTreeAllowLogin/'+inData.roleId,
                    success: function(id, url, searchVal, result){
                        try {
                            //动态改变人员选择显示的高度
                            $('.xm-select')[0].removeAttribute('xm-hg');
                            var height = $('.layui-layer-content')[0].style.height;
                            height = parseInt(height.replace('px', ''));
                            $('.xm-select-label')[0].style.height = (height - 20) + "px";
                        } catch (e) {}
                        console.log('id: userSelect, 成功返回数据!!!');
                    }
                });
                formSelects.filter('userSelect', function(id, inputVal, choice, isDisabled){
                    if(choice.name.indexOf(inputVal) != -1){
                        return false;
                    }
                    return true;
                });
            },
            callBack: function (index, layero) {
                top.Feng.loading();
                var userIds = formSelects.value('userSelect', 'valStr');
                var ajax = new $ax(Feng.ctxPath + "/userRole/userRoleAuthority", function (data) {
                    Feng.success("分配角色成功!");
                    layer.close(index);
                    top.Feng.closeLoading();
                }, function (data) {
                    top.Feng.closeLoading();
                    Feng.error("分配角色失败!" + data.responseJSON.message + "!");
                    return false;
                });
                ajax.setAsync(true);
                ajax.set("userIds", userIds);
                ajax.set("roleId", inData.roleId);
                ajax.start();
            },
            end: function(){
                // table.reload(Role.tableId);
            }
        };
        Feng.openModal(options);
    };

    // 渲染表格
    var tableResult = table.render({
        elem: '#' + Role.tableId,
        url: Feng.ctxPath + '/role/list',
        page: true,
        height: "full-98",
        cellMinWidth: 100,
        cols: Role.initColumn()
    });

    // 搜索按钮点击事件
    $('#btnSearch').click(function () {
        Role.search();
    });

    $('#btnReset').click(function () {
        $('#roleName').val('');
    });

    // 添加按钮点击事件
    $('#btnAdd').click(function () {
        Role.openAddRole();
    });

    // 导出excel
    $('#btnExp').click(function () {
        Role.exportExcel();
    });

    // 工具条点击事件
    table.on('tool(' + Role.tableId + ')', function (obj) {
        var data = obj.data;
        var layEvent = obj.event;

        if (layEvent === 'edit') {
            Role.onEditRole(data);
        } else if (layEvent === 'delete') {
            Role.onDeleteRole(data);
        } else if (layEvent === 'roleAssign') {
            Role.roleAssign(data);
        } else if (layEvent === 'roleUserAssign') {
            Role.roleUserAssign(data);
        }
    });
});
